<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<section>
    <h4>链表</h4>
    <ul>
        <li>新增</li>
        <li>删除</li>
        <li>修改</li>
        <li>遍历或打印</li>
    </ul>
</section>
<script>
    class Node {
        constructor(val) {
            this.val = val;
            this.next = null;
        }
    }

    class LinkNodeList {
        constructor() {
            this.head = null;
            this.length = 0;
        }

        add(val) {
            const node = new Node(val);
            if (this.head) {
                let cur = this.head;
                while (cur.next) {
                    cur = cur.next;
                }
                cur.next = node;
            } else {
                this.head = node;
            }
            this.length += 1;
        }

        remove(val) {
            let cur = this.head;
            let prev = null;
            while(cur) {
                if (cur.val === val) {
                    if (prev) {
                        prev.next = cur.next ? cur.next : null;
                        cur.next = null;
                    } else {
                        this.head = this.head.next;
                    }
                    this.length--;
                    return cur.val;
                }
                prev = cur;
                cur = cur.next;
            }
        }

        removeAt(index) {
            let cur = this.head;
            let prev = null;
            let count = 0;
            while(cur) {
                if (index === count) {
                    if (prev) {
                        prev.next = cur.next ? cur.next : null;
                        cur.next = null;
                    } else {
                        this.head = this.head.next;
                    }
                    this.length--;
                    return cur.val;
                }

                prev = cur;
                cur = cur.next;
                count++;
            }
        }

        toString() {
            const arr = [];
            let cur = this.head;
            while(cur) {
                arr.push(cur.val);
                cur = cur.next;
            }
            return arr.join('=>');
        }
    }

    const linkedNodeList = new LinkNodeList();
    linkedNodeList.add(1);
    linkedNodeList.add(2);
    linkedNodeList.add(3);
    console.log(linkedNodeList.toString());
    linkedNodeList.removeAt(0);
    console.log(linkedNodeList.toString());
</script>
</body>
</html>
